
interface HttpOptions extends RequestInit {
  timeout?: number;
  headers?: Record<string, string>;
  body?: BodyInit | null | undefined; // 允许普通对象
}



const http = {
  /**
   * 基础请求方法
   * @param {string} url 请求地址
   * @param {Object} options 请求配置
   * @returns {Promise} 返回处理后的Promise
   */

  fetchRequest(url: string, options?: HttpOptions) {
    let userOption = options
    if (!userOption) {
      userOption = {}
    }
    // 默认配置
    // 默认配置
    const defaults: HttpOptions = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...userOption.headers,
      },
      credentials: 'include',
    };

    // 合并配置
    const config: HttpOptions & { timeout?: number } = { ...defaults, ...options };

    // 处理body（对象自动转换为JSON）
    if (config.body && typeof config.body === 'object' && !(config.body instanceof FormData)) {
      config.body = JSON.stringify(config.body);
    }

    // 超时控制
    const timeout = config.timeout || 10000;
    const abortController = new AbortController();
    config.signal = abortController.signal;
    const timeoutId = setTimeout(() => {
      abortController.abort();
    }, timeout);

    // 发送请求
    return fetch(url, config as RequestInit)
      .then(response => {
        clearTimeout(timeoutId);

        // HTTP状态码错误处理
        if (!response.ok) {
          return response.json().then(err => {
            throw new Error(`HTTP错误 ${response.status}: ${err.message || response.statusText}`);
          }).catch(() => {
            throw new Error(`HTTP错误 ${response.status}: ${response.statusText}`);
          });
        }

        // 自动解析JSON
        const contentType = response.headers.get('content-type');
        return contentType && contentType.includes('application/json')
          ? response.json()
          : response.text();
      })
      .catch(error => {
        clearTimeout(timeoutId);
        if (error.name === 'AbortError') {
          throw new Error(`请求超时（${timeout}ms）`);
        }
        throw new Error(`网络错误: ${error.message}`);
      });
  },

  // 快捷方法
  get(url: string, options?: HttpOptions) {
    return this.fetchRequest(url, { ...options, method: 'GET' });
  },

  post(url: string, body: HttpOptions['body'], options?: HttpOptions) {
    return this.fetchRequest(url, { ...options, method: 'POST', body });
  },

  put(url: string, body: HttpOptions['body'], options?: HttpOptions) {
    return this.fetchRequest(url, { ...options, method: 'PUT', body });
  },

  delete(url: string, options?: HttpOptions) {
    return this.fetchRequest(url, { ...options, method: 'DELETE' });
  },
};

export default http;

// // 使用示例
// http.get('https://api.example.com/data')
//   .then(data => console.log('成功:', data))
//   .catch(err => console.error('失败:', err.message));

// http.post('https://api.example.com/post', { key: 'value' })
//   .then(data => console.log('成功:', data))
//   .catch(err => console.error('失败:', err.message));